<template>
  <div class="dashboard">
    <a-spin :spinning="loading">
      <!-- 顶部统计卡片 -->
      <a-row :gutter="24">
        <a-col v-for="(item, index) in statsData" :key="index" :xl="6" :lg="12" :md="12" :sm="24" :xs="24">
          <a-card class="dashboard-card" :bordered="false">
            <div class="card-header">
              <a-icon :type="item.icon" class="card-icon" />
              <span class="card-title">{{ item.title }}</span>
            </div>
            <div class="card-content">
              <div v-for="(stat, i) in item.stats" :key="i" class="card-statistic">
                <div :class="stat.class">{{ stat.value }}</div>
                <div class="statistic-label">{{ stat.label }}</div>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>

      <a-row :gutter="24" class="mt-24">
        <!-- 左侧内容 -->
        <a-col :xl="16" :lg="24" :md="24" :sm="24" :xs="24">
          <!-- 生产进度跟踪 -->
          <a-card class="dashboard-section" :bordered="false">
            <template slot="title">
              <span>生产进度跟踪</span>
              <a-select v-model="timeRange" style="width: 120px; margin-left: 16px" size="small">
                <a-select-option value="week">本周</a-select-option>
                <a-select-option value="month">本月</a-select-option>
              </a-select>
            </template>
            <a-row :gutter="16">
              <a-col :span="12">
                <div class="progress-item">
                  <div class="progress-header">
                    <span>计划总数</span>
                    <span class="progress-value">{{ production.total || 0 }}</span>
                  </div>
                  <a-progress :percent="production.rate || 0" :stroke-color="getProgressColor(production.rate)" />
                  <div class="progress-footer">
                    <span>已完成: {{ production.completed || 0 }}</span>
                    <span>进行中: {{ production.processing || 0 }}</span>
                  </div>
                </div>
              </a-col>
              <a-col :span="12">
                <div class="progress-item">
                  <div class="progress-header">
                    <span>延期任务</span>
                    <span class="progress-value text-danger">{{ production.delayed || 0 }}</span>
                  </div>
                  <a-progress :percent="production.delayedRate || 0" status="exception" />
                  <div class="progress-footer">
                    <span>正常: {{ production.total - production.delayed || 0 }}</span>
                    <span>延期率: {{ production.delayedRate || 0 }}%</span>
                  </div>
                </div>
              </a-col>
            </a-row>
          </a-card>

          <!-- 快速操作 -->
          <a-card class="dashboard-section mt-24" :bordered="false">
            <template slot="title">
              <span>快速操作</span>
            </template>
            <div class="quick-actions">
              <a-row :gutter="[16, 24]">
                <a-col :span="6" v-for="(action, i) in quickActions" :key="i">
                  <a-button block type="link" @click="handleAction(action.key)">
                    <a-icon :type="action.icon" class="action-icon" />
                    <div class="action-title">{{ action.title }}</div>
                  </a-button>
                </a-col>
              </a-row>
            </div>
          </a-card>
        </a-col>

        <!-- 右侧内容 -->
        <a-col class="right-side" :style="{ paddingLeft: '0 !important' }" :xl="8" :lg="24" :md="24" :sm="24" :xs="24">
          <!-- 库存预警 -->
          <a-card class="dashboard-section" :bordered="false">
            <template slot="title">
              <span>库存预警</span>
              <a-button type="link" size="small" @click="viewMoreWarnings">更多</a-button>
            </template>
            <a-list item-layout="horizontal" :data-source="warnings">
              <a-list-item slot="renderItem" slot-scope="item">
                <a-list-item-meta>
                  <a-avatar slot="avatar" :style="{ backgroundColor: getWarningColor(item.level), color: '#fff' }">
                    {{ getWarningText(item.level) }}
                  </a-avatar>
                  <div slot="title">
                    {{ item.name }}
                    <span class="warning-desc">{{ item.desc }}</span>
                  </div>
                  <div slot="description" class="warning-info">
                    <span>当前库存: {{ item.current }}</span>
                    <span>安全库存: {{ item.safe }}</span>
                  </div>
                </a-list-item-meta>
              </a-list-item>
              <div v-if="warnings.length === 0" class="no-data">
                <a-empty description="暂无预警信息" />
              </div>
            </a-list>
          </a-card>
        </a-col>
      </a-row>
    </a-spin>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import ChartCard from '@/components/ChartCard'
import { getDashboardStats } from '@/api/dashboard'

export default {
  name: 'Dashboard',
  components: {
    ChartCard,
  },
  data() {
    return {
      loading: true,
      timeRange: 'week',
      statsData: [
        {
          title: '订单概览',
          icon: 'shopping-cart',
          stats: [
            { label: '总订单', value: 0 },
            { label: '待处理', value: 0, class: 'text-warning' },
            { label: '已完成', value: 0, class: 'text-success' },
          ],
        },
        {
          title: '生产状态',
          icon: 'build',
          stats: [
            { label: '总计划', value: 0 },
            { label: '进行中', value: 0, class: 'text-warning' },
            { label: '已完成', value: 0, class: 'text-success' },
          ],
        },
        {
          title: '库存状态',
          icon: 'inbox',
          stats: [
            { label: '总品类', value: 0 },
            { label: '库存不足', value: 0, class: 'text-danger' },
            { label: '即将到期', value: 0, class: 'text-warning' },
          ],
        },
        {
          title: '财务概览',
          icon: 'dollar',
          stats: [
            { label: '应收款', value: '¥0' },
            { label: '应付款', value: '¥0', class: 'text-danger' },
            { label: '本月利润', value: '¥0', class: 'text-success' },
          ],
        },
      ],
      production: {
        total: 0,
        completed: 0,
        processing: 0,
        delayed: 0,
        rate: 0,
        delayedRate: 0,
      },
      warnings: [],
      quickActions: [
        { key: 'newOrder', title: '新建订单', icon: 'file-add' },
        { key: 'inventory', title: '物料库存', icon: 'edit' },
        { key: 'inbound', title: '物料入库单', icon: 'import' },
        { key: 'outbound', title: '物料出库单', icon: 'export' },
        { key: 'finishedInventory', title: '成品库存', icon: 'team' },
        { key: 'finishedInbound', title: '成品入库单', icon: 'inbox' },
        { key: 'finishedOutbound', title: '成品出库单', icon: 'search' },
        { key: 'plan', title: '生产计划', icon: 'schedule' },
      ],
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  mounted() {
    this.fetchDashboardData()
  },
  methods: {
    async fetchDashboardData() {
      this.loading = true
      try {
        console.log('Fetching dashboard data...')
        const response = await getDashboardStats()
        console.log('Dashboard API response:', response)

        // Handle case where response is the data directly
        const result = response.result || response

        if (!result) {
          throw new Error('Invalid response format from server')
        }

        this.production = {
          total: result.totalProduction || 0,
          completed: result.completedProduction || 0,
          processing: result.processingProduction || 0,
          delayed: result.delayedProduction || 0,
          rate: result.completionRate || 0,
          delayedRate: result.delayedRate || 0,
        }

        // 转换警告数据格式
        this.warnings = (result.recentWarnings || []).map((item) => {
          // 将后端的 level 值映射为前端使用的 level 值
          const levelMap = {
            high: 'high',
            medium: 'medium',
            low: 'low',
            1: 'high',
            2: 'medium',
            3: 'low',
          }

          return {
            id: item.id,
            name: item.name || '未知物料',
            desc: item.desc || '库存异常',
            current: parseFloat(item.current) || 0,
            safe: parseFloat(item.safe) || 0,
            level: levelMap[item.level] || 'medium',
          }
        })

        // 更新统计数据
        this.statsData = [
          {
            title: '订单概览',
            icon: 'shopping-cart',
            stats: [
              { label: '总订单', value: result.totalProduction || 0 },
              { label: '待处理', value: result.pendingTasks || 0, class: 'text-warning' },
              { label: '已完成', value: result.completedTasks || 0, class: 'text-success' },
            ],
          },
          {
            title: '生产状态',
            icon: 'build',
            stats: [
              { label: '总计划', value: result.totalProduction || 0 },
              { label: '进行中', value: result.processingProduction || 0, class: 'text-warning' },
              { label: '已完成', value: result.completedProduction || 0, class: 'text-success' },
            ],
          },
          {
            title: '库存状态',
            icon: 'inbox',
            stats: [
              { label: '总品类', value: result.totalWarnings || 0 },
              {
                label: '库存不足',
                value: result.highLevelWarnings + result.mediumLevelWarnings || 0,
                class: 'text-danger',
              },
              { label: '库存正常', value: result.lowLevelWarnings || 0, class: 'text-success' },
            ],
          },
          {
            title: '任务完成率',
            icon: 'rise',
            stats: [
              { label: '完成率', value: `${result.taskCompletionRate || 0}%` },
              { label: '待处理', value: result.pendingTasks || 0, class: 'text-warning' },
              { label: '已完成', value: result.completedTasks || 0, class: 'text-success' },
            ],
          },
        ]
      } catch (error) {
        console.error('获取仪表盘数据失败:', error)
        this.$message.error('获取数据失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    getProgressColor(percent) {
      if (percent < 50) return '#f5222d'
      if (percent < 80) return '#faad14'
      return '#52c41a'
    },
    getWarningColor(level) {
      const colors = {
        high: '#f5222d',
        medium: '#faad14',
        low: '#52c41a',
        default: '#d9d9d9',
      }
      return colors[level] || '#d9d9d9'
    },
    getWarningText(level) {
      const texts = {
        high: '高',
        medium: '中',
        low: '低',
        default: '未知',
      }
      return texts[level] || '未知'
    },
    viewMoreWarnings() {
      // 使用JeecgBoot推荐的路由跳转方式跳转到库存预警页面
      this.$router.push({ path: '/wms/purchase/MaterialWarningList' })
    },
    handleAction(key) {
      const routes = {
        newOrder: '/oms/product/ProductOrderList',
        inventory: '/wms/inventory/InventoryList',
        inbound: '/wms/inboundOrder/list',
        outbound: '/wms/outbound/OutboundList',
        finishedInventory: '/wms/finishedGoods/InventoryList',
        finishedInbound: '/wms/finishedGoods/InboundList',
        finishedOutbound: '/wms/finishedGoods/FinishedGoodsOutboundList',
        plan: '/mes/plan/PlanList',
      }
      if (routes[key]) {
        // 使用JeecgBoot推荐的路由跳转方式
        this.$router.push({ path: routes[key] })
      }
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@/components/index.less';

@primary-color: #1890ff;
@success-color: #67c23a;
@error-color: #f56c6c;
@warning-color: #e6a23c;
@text-color: #303133;
@text-color-secondary: #909399;
@border-color: #ebeef5;
@background-color: #f5f7fa;
@card-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

.mt-24 {
  margin-top: 10px;
}

.dashboard {
  padding: 10px;
  background: #f0f2f5;
  min-height: 100%;

  .dashboard-card {
    margin-bottom: 24px;
    border-radius: 4px;
    box-shadow: 0 1px 2px -2px rgba(0, 0, 0, 0.16), 0 3px 6px 0 rgba(0, 0, 0, 0.12), 0 5px 12px 4px rgba(0, 0, 0, 0.09);

    .card-header {
      display: flex;
      align-items: center;
      margin-bottom: 16px;

      .card-icon {
        font-size: 20px;
        margin-right: 8px;
        color: @primary-color;
      }

      .card-title {
        font-size: 16px;
        font-weight: 500;
        color: @text-color;
      }
    }

    .card-content {
      display: flex;
      justify-content: space-between;

      .card-statistic {
        text-align: center;

        .statistic-value {
          font-size: 24px;
          font-weight: 600;
          margin-bottom: 4px;

          &.text-success {
            color: #52c41a;
          }

          &.text-warning {
            color: #faad14;
          }

          &.text-danger {
            color: #f5222d;
          }
        }

        .statistic-label {
          color: rgba(0, 0, 0, 0.45);
          font-size: 14px;
        }
      }
    }
  }

  .dashboard-section {
    border-radius: 12px;
    box-shadow: @card-shadow;
    transition: all 0.3s ease;
    margin-bottom: 16px;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    }

    .ant-card-head-title {
      font-weight: 500;
    }
  }

  .ant-card-body {
    padding: 16px 24px;
  }
}

.progress-item {
  padding: 8px 0;

  .progress-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;

    .progress-value {
      font-weight: 600;

      &.text-danger {
        color: @error-color;
      }
    }
  }

  .progress-footer {
    display: flex;
    justify-content: space-between;
    margin-top: 8px;
    font-size: 12px;
    color: @text-color-secondary;
  }

  /deep/ .ant-progress-text {
    font-size: 12px;
  }
}

.quick-actions {
  .action-icon {
    font-size: 24px;
    margin-bottom: 8px;
    color: @primary-color;
  }

  .action-title {
    font-size: 12px;
    color: @text-color;
    margin-top: 4px;
  }

  /deep/ .ant-btn-link {
    padding: 16px 0;
    height: auto;
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      background-color: fade(@primary-color, 8%);
      transform: translateY(-2px);
    }
  }

  .ant-btn {
    height: auto;
    padding: 16px 0;
  }
}

.warning-desc {
  margin-left: 8px;
  font-size: 12px;
  color: #f5222d;
}

.warning-info {
  display: flex;
  justify-content: space-between;
  margin-top: 4px;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
}

.no-data {
  padding: 24px 0;
  text-align: center;
}

// 响应式调整
@media (max-width: 768px) {
  .dashboard {
    padding: 12px;

    .dashboard-card {
      margin-bottom: 12px;

      .card-content {
        flex-wrap: wrap;

        .card-statistic {
          width: 50%;
          margin-bottom: 12px;

          .statistic-value {
            font-size: 20px;
          }
        }
      }
    }
  }
}
</style>
